<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :title="$t('locationBarcodeInfo.locationBarcodeDetails')" scanType="0"></nav-bar-custom>
		</template>

		<template v-slot:gBody>
			<view class="distributed">
				<view class="gui-bg-white gui-dark-bg-level-3 gui-padding-x distributed-head">
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="gui-form-label gui-secondary-text">{{ $t('warehousing.libraryBitCode') }}</text>
						<uni-easyinput ref="locationInput"  class="uni-mt-5" suffixIcon="scan" v-model="data.locationCodes"
							:placeholder="$t('warehousing.scanLocation')" @blur="data.focus = false" :focus="!data.focus"
							@confirm="confirmLocation" @iconClick="iconClickLocation">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="gui-form-label gui-secondary-text">{{ $t('distributedEnter.barcodeScan') }}</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan2" v-model="data.barcode" @focus="data.focus = false" 
							:focus="data.focus" type="search" @confirm="confirm" @iconClick="iconClick"
							:placeholder="$t('stockManage.pleaseScanCode')">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="gui-form-label gui-secondary-text">{{ $t('distributedEnter.materialCode') }}</text>
						<comboGrid requestUrl="/mes/basMaterial/getPageSetPDA" v-model="data.materialCode"
							:requestParam="data.materialParam" inputKey="materialName"
							:showClear="!!data.materialCode"
							:placeholder="$t('distributedEnter.placeholderTextChoose')"
							:gridPlaceholder="$t('Common.enterCodeOrName')" :column="data.columnName.column"
							bindValue="materialName" @setClick="getMaterialClick" @onClear='setClear'>
						</comboGrid>
					</view>

					<view class="gui-form-item gui-border-b gui-flex gui-justify-content-center">
						<view class="gui-flex gui-space-between gui-align-items-center" style="width: 70%;height: 100rpx;">
							<button type="default" class="gui-button gui-button-mini gui-bg-black4 gui-noborder"
								style="width:200rpx;" @click="reset(OPERATION_REASCT)">
								<text class="gui-block gui-color-black gui-button-text-mini gui-icons">{{
									$t('distributedEnter.reset') }}</text>
							</button>
							<button type="default" class="gui-button gui-button-mini gui-bg-blue gui-noborder"
								style="width:200rpx;" @click="search">
								<text class="gui-block gui-color-white gui-button-text-mini gui-icons">{{
									$t('distributedEnter.search') }}</text>
							</button>
						</view>
					</view>
				</view>
						<!-- 汇总信息 -->
					<view class="card-boxCustom gui-transition-all  defective-box" style="margin: 20rpx 24rpx 0;"
						v-if="data.list.length">
						<view class="card-body" style="padding-bottom: 15rpx;" @click.stop="clickShowList">
							<view class="card-rotating">
								<uni-icons v-if="data.showList" type="bottom" color="#9C9C9C"
									size="20"></uni-icons>
								<uni-icons v-else type="top" color="#9C9C9C" size="20"></uni-icons>
							</view>
							<view class="custom-card-title">
								<text class="title-line"></text>
								{{ $t('taskList.materialSum') }}
							</view>
							<view class="card-body-item item">
								<text class="body-item-title" style="margin-right: 16rpx;">{{ $t('distributedEnter.totalItemsOfMaterials') }}：<text style="color:#333333;">{{ data.countMaterial }}</text></text>
								<text class="body-item-title" style="margin-right: 16rpx;">{{ $t('distributedEnter.totalNumberOfBarcodes') }}：<text style="color:#333333;">{{ data.countBarcode }}</text> </text>
								<text class="body-item-title" style="margin-right: 16rpx;">{{ $t('distributedEnter.totalNumberOfMaterials') }}：<text style="color:#333333;">{{ data.sumQty }}</text> </text>
							</view>
		
						</view>
						<view class="card-body-folding" v-show="data.showList">
							<view class="card-body-item" v-for="(x, i) in data.totalSum" :key="i">
								<text class="body-item-title" style="margin-right: 16rpx;">{{ $t('distributedEnter.materialCode') }}：<text style="color:#333333;">{{  x.materialCode }}</text></text>
								<text class="body-item-title" style="margin-right: 16rpx;">{{ $t('distributedEnter.qty') }}：<text style="color:#333333;">{{  x.sumQty }}</text></text>
								<text class="body-item-title">{{ $t('translationImage.numberOfBarcodes') }}：<text style="color:#333333;">{{ x.countBarcode  }}</text></text>
							</view>
						</view>
					</view>
				<!-- 底部显示区域 -->
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll" @scrolltolower="scrolltolower">
					<view style="height: 15rpx"></view>
	
					<view class="record-card" v-for="(list, index) in data.list" :key="index">
						<!-- <uni-icons class="close-icons" type="closeempty" color="#9C9C9C" size="30"
							@click="deletList(index, list)"></uni-icons> -->
						<view class="card-mini-head">
							<view class="title-line"></view>
							<text>{{ $t('translationImage.serialNumber') }}：{{ index + 1 }}</text>
						</view>
						<view class="custom-card-itemOne">
							<text class="item-info-title">{{ $t('distributedEnter.materialCoded') }}：</text>{{
								list.barcode }}
						</view>
						<view class="custom-card-itemOne">
							<text class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{
								list.materialCode }}
						</view>
						<view class="custom-card-itemOne">
							<text class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>{{
								list.materialName }}
						</view>
						<view class="custom-card-itemOne">
							<text class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{
								list.materialSpec }}
						</view>
						<view class="custom-card-itemOne">
							<view class="card-item-50">
								<text class="item-info-title">{{ $t('distributedEnter.qty') }}：</text>{{ list.currentQty }}
							</view>
							<view class="card-item-50">
								<text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{ list.unit }}
							</view>
						</view>
						<view class="custom-card-itemOne">
							<view class="card-item-50">
								<text class="item-info-title">{{ $t('distributedOut.warehouse')
								}}：</text>{{ list.warehouseCode }}
							</view>
							<view class="card-item-50">
								<text class="item-info-title">{{ $t('distributedOut.location') }}：</text>{{
									list.locationCode }}
							</view>
						</view>
						<view class="custom-card-itemOne gui-flex gui-justify-content-end">
							<view class="print-class" @click="handelPrint(list)">
								{{ $t('multilingual.printBarcode') }}
							</view>
						</view>
					</view>
					<view v-if="data.noticeHooks" class="noticeHooks">
						{{ data.list.length == 0 ? $t('stockManage.notAvailable') : $t('stockManage.without') }}
					</view>
				</scroll-view>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import pdaScan from '@/hooks/pdaScan.js'
import { useStore } from "vuex";
import { BIGBARCODER_PRINT } from '@/constant/index.js'
import { getDataDictionaryFn } from '@/utils/index.js'
import storageBin from '@/components/storageBin.vue'
import comboGrid from '@/components/comboGrid.vue'
import { onShow } from '@dcloudio/uni-app';
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_SCAN } from '@/constant/index.js'
import { barcodeByCondition, wmsSelectWmsBarcodeInfo,getProductionRetreatBarcode, printsLabels1  } from '@/api/api.js'
import { ref, reactive, onMounted, watch, computed, toRaw } from 'vue';
import { OPERATION_SEARCH, OPERATION_REASCT, OPERATION_LOOK, OPERATION_CHOOSE } from '@/constant/index.js'
import tableColor from '@/hooks/tableColor.js'

//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

components: {
	storageBin,
		comboGrid
}
const storageBinRef = ref(null)
const comboGridRef = ref(null)

const { scan } = pdaScan()
let store = useStore();

const navHeight = computed(() => {
	return store.state.navHeight
})

let { tableData } = tableColor();
const { cellStyle, cellHeaderStyle } = tableColor();
const locationInput = ref()

let data = reactive({
	barcode: '', //条码
	materialCode: '', //物料代码
	materialId: '',
	locationId: '',//目的库位
	idlocationName: '',// 选中库位
	locationCodes: '',
	focus: true,
	// 物料代码
	materialParam: {
		materialCode: "",
		materialName: "",//物料代码,传给接口用的变量
		text: ""
	},
	//物料代码下面的筛选
	columnName: {
		column: [{
			label: t('distributedEnter.materialCode'),
			name: "materialCode",
		}, {
			label: t('distributedEnter.materialName'),
			name: "materialName",
		}, {
			label: t('distributedEnter.materialSpec'),
			name: "specification",
		}]
	},
	page: 1,
	rows: 10,
	noticeHooks: false, //暂无相关数据标识
	list:[],
	collect:[],
	barcodeList: [],//扫描的条码数组
	countBarcode:'',
	countMaterial:'',
	sumQty:'',
	showList:false
})
onMounted(() => {
	uni.$on('scancodedate', (itme) => {
		console.log('获取到的code：' + itme.code, data.focus)
		if (data.focus) {
			getCode(itme.code, 'pda')
		}
		if (data.focus == false) {
			getCodeLocation(itme.code, 'pda')
		}
	})

})
const clickShowList = () =>{
	data.showList = data.showList ? false :true
}
const setClear = () =>{
	data.materialParam.materialCode = '';
	data.materialParam.materialName = '';
	data.materialCode = '';
	data.materialName = '';
	data.unit = '';
	data.materialSpec = '';
	data.materialId = '';
}
//物料名称的选择
const getMaterialClick = (x) => {
	data.materialParam.materialCode = x.materialCode;
	data.materialParam.materialName = x.materialName;
	data.materialCode = x.materialCode;
	data.materialName = x.materialName;
	data.unit = x.unit
	data.materialSpec = x.specification
	data.materialId = x.id
}

// 用户点击扫码图标 条码
const iconClick = async (type) => {
	data.focus = false
	if (type === 'suffix') {
		let code = await scan()
		if (!data.focus) {
			getCode(code, 'scan2')
		}
	}
}
// 用户点击搜索  条码
const confirm = () => {
	data.focus = false
	if (!data.focus) {
		getCode(data.barcode, 'keydown')
	}
}

// 获取code
const getCode = async (code, type) => {

     const validPrefixPattern = /^(M|T|RAW|WIP|WJ)/; // 条码
	 if (validPrefixPattern.test(code)){
			data.barcode = code
	 }else {
    	data.barcode = ''
		data.locationCodes =  code
	 }


	let parmes = {
		barcode: code,
		selectType: 'splitBarcode'
	}
	uni.showLoading({
		title: 'loading',
		mask: true
	});

	let res = await wmsSelectWmsBarcodeInfo(parmes)
	try {
		let inputParameter = JSON.stringify(parmes)
		let returnParameter = JSON.stringify(res)
		let operationPicture = '库位条码详情'
		let callInterface = res.rquestUrl
		let opertionParmes = {
			inputParameter,
			returnParameter,
			operationPicture,
			callInterface,
			responseCode: res.status,//返回状态
			errorMessage: res.message,//错误信息
			isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
			operationType: OPERATION_SCAN
		}
		basPdaOperationLogFn(opertionParmes)
	} catch (error) {
	}
	if (res.status == 200) {
		data.barcode = res.data.barcode
		//隐藏加载框
		uni.hideLoading();

	} else {
		data.barcode = ''
		data.focus = true
		uni.showToast({ title: res.message, icon: "none" })
	}
}

// 用户调起相机扫码 库位
const iconClickLocation = async (type) => {
	data.focus = true
	if (type === 'suffix') {
		let code = await scan()
		getCodeLocation(code, 'scan')
	}
}
// 用户点击键盘上搜索 库位
const confirmLocation = () => {
	data.focus = true
	getCodeLocation(data.locationCodes, 'keydown')
}
// 获取code
const getCodeLocation = (code, type) => {
	 const validPrefixPattern = /^(M|T|RAW|WIP|WJ)/; // 条码
	 if (validPrefixPattern.test(code)){
			data.barcode = code
			data.locationCodes = ''
			data.focus = false
	 }else {
    	data.barcode = ''
		data.locationCodes =  code
	 }
}

// 重置
const reset = async (type) => {
	data.barcode = ''
	data.materialCode = ''
	data.locationCodes = ''
	data.focus=true
}

//上拉加载
const scrolltolower = () => {
	if (!data.noticeHooks) {
		data.page++
		getLocaitonData()
	}
}

// 查询
const search = () => {
	data.operationType = OPERATION_SEARCH
	const code = data.locationCodes || data.barcode
	const validPrefixPattern = /^(M|T|RAW|WIP|WJ)/; // 条码
	 if (validPrefixPattern.test(code)){
			data.barcode = code
			data.locationCodes =  ''
	 }else {
    	data.barcode = ''
		data.locationCodes =  code
	 }
	data.page = 1
	getLocaitonData()
}
const getLocaitonData = () => {
	barcodeByCondition({
		page: data.page,
		rows: data.rows,
		locationCode: data.locationCodes,
		barcode: data.barcode,
		materialCode: data.materialCode
	}).then(res => {
		if (res.status == 200) {
			data.noticeHooks = false
			if (data.page === 1) {
				if (res.data.data.rows.length == 0) {
					data.noticeHooks = true
				}
				data.list = res.data.data.rows
				data.list.forEach(element => {
					element.openBool = false
				});
			} else {
				let arr = res.data.data.rows
				arr.forEach(element => {
					element.openBool = false
				});
				data.list = [...data.list, ...arr]
			}
			data.noticeHooks = data.list.length >= res.data.data.total
			data.totalSum=res.data.materialList
			data.countBarcode=res.data.countBarcode
			data.countMaterial=res.data.countMaterial
			data.sumQty=res.data.sumQty
		}
	})
}

// 打印
const handelPrint = (item) => {
	console.log(item)
	// return
	if (item == null) {
		uni.showToast({ title: t('stockManage.pleaseScanCode'), icon: "none" });
		return
	}
	let defaultValue = uni.getStorageSync(BIGBARCODER_PRINT) || ''
	let parmase = {
		barCode: item.barcode,
		materialCode: item.materialCode,
		materialName: item.materialName,
		specification: item.materialSpec,
		LocationCode:item.locationCode,
		produceDate: item.produceDate ? item.produceDate.slice(0, 10) : '', // 生产日期
		hostid: item.equipmentCode || '', //机台
		qty: item.currentQty,
		uuit: item.unit, //单位
		printerName: defaultValue //打印机名字
	}
	console.log(parmase)
	uni.showLoading({
		title: t('materials.connecting')
	});
	printsLabels1(parmase).then(res => {
		try {
			let inputParameter = JSON.stringify(parmase)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '库位条码详情'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_PRINT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res, 'reessss')
		uni.hideLoading();
		if (res.status == 200) {
			uni.showToast({ title: t('JsInternational.printSuccessfully'), icon: "none" });
		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	}).catch(() => {
		try {
			let inputParameter = JSON.stringify(parmase)
			let returnParameter = '无'
			let operationPicture = '库位条码详情'
			let callInterface = printUrl + "/print/RawMaterialBarCodePrint"
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: 408,//返回状态
				errorMessage: '请求超时',//错误信息
				isPass: 'N',//是否成功 Y N
				operationType: OPERATION_PRINT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		uni.showToast({ title: t('materials.printingFailed'), icon: "none" });
		uni.hideLoading();
	})
}

</script>

<style lang="scss" scoped>
.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.noticeHooks {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 80rpx;
	font-size: 32rpx;
	color: #999;
}

.distributed {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.item {
	position: relative;

	.tags {
		position: absolute;
		right: 0;
		top: 0;
	}
}

.print-class {
	display: inline-block;
	padding: 10rpx 20rpx;
	background-color: chartreuse;
	color: #fff;
	border-radius: 8rpx;
	background: $uni-color-teal;
}
.tableLineHeight {
	height: 60rpx;
	min-width: 630rpx !important;
}

.tableLine {
	padding: 0 20rpx !important;
	box-sizing: border-box;
}

.uni-table-loading {
	height: 60rpx !important;
}
</style>
